package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.domain.TSmjGoodList;
import com.ruoyi.business.domain.TSmjMachineList;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.BasePayment;
import com.ruoyi.business.service.CommonService;
import com.ruoyi.business.service.ITSmjGoodListService;
import com.ruoyi.business.service.ITSmjMachineListService;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtil;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

@Service("smjmsxlmPayService")
public class SmjmsXlmPayService extends BasePayment {

    @Resource
    public ITSmjMachineListService itSmjMachineListService;
    @Resource
    public ITSmjGoodListService itSmjGoodListService;
    @Resource
    private CommonService commonService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysConfigService sysConfigService;

    private TSmjGoodList getPayInfoObj(TRecipientInfo tUserRecipientInfo, TOrderInfo tOrderInfo) {
        List<TSmjGoodList> tSmjGoodLists = null;
        BigDecimal amount = new BigDecimal(tOrderInfo.getMoney() / 100).setScale(2);
        if (tOrderInfo.getChannel().contains("alipay")) {
            if (redisUtil.get("PLATFORM_SMJXLMALI"+tUserRecipientInfo.getId()+amount) == null || ((List<TSmjGoodList>) redisUtil.get("PLATFORM_SMJXLMALI"+tUserRecipientInfo.getId()+amount)).size() == 0) {
                TSmjGoodList query = new TSmjGoodList();
                query.setRealChannelCode(tOrderInfo.getChannel());
                query.setUserId(tUserRecipientInfo.getUserId());
                query.setGoodStatus(0);
                query.setPayType("ALI");
                query.setGoodPrice(amount);
                tSmjGoodLists = itSmjGoodListService.selectTSmjGoodListListByNoAuth(query);
                if (tSmjGoodLists.size() == 0) {
                    return null;
                }
                logger.info("缓存中无金额对应的商品：重新获取生产缓存，{}", tSmjGoodLists.size());
            } else {
                logger.info("缓存中有金额对应的商品：获取第一个商品");
                tSmjGoodLists = (List<TSmjGoodList>) redisUtil.get("PLATFORM_SMJXLMALI"+tUserRecipientInfo.getId()+amount + "");
            }
        } else {
            if (redisUtil.get("PLATFORM_SMJXLMWX"+tUserRecipientInfo.getId()+amount) == null || ((List<TSmjGoodList>) redisUtil.get("PLATFORM_SMJXLMWX"+tUserRecipientInfo.getId()+amount)).size() == 0) {
                TSmjGoodList query = new TSmjGoodList();
                query.setRealChannelCode(tOrderInfo.getChannel().replace("alipay", "wechat"));
                query.setUserId(tUserRecipientInfo.getUserId());
                query.setGoodStatus(0);
                query.setPayType("WX");
                query.setGoodPrice(amount);
                tSmjGoodLists = itSmjGoodListService.selectTSmjGoodListListByNoAuth(query);
                if (tSmjGoodLists.size() == 0) {
                    return null;
                }
                logger.info("缓存中无金额对应的商品：重新获取生产缓存，{}", tSmjGoodLists.size());
            } else {
                logger.info("缓存中有金额对应的商品：获取第一个商品");
                tSmjGoodLists = (List<TSmjGoodList>) redisUtil.get("PLATFORM_SMJXLMWX"+tUserRecipientInfo.getId()+amount + "");
            }
        }
        Collections.shuffle(tSmjGoodLists);
        logger.info("获取金额为：{}的商品前缓存的商品个数：{}", amount, tSmjGoodLists.size());
        TSmjGoodList tmpSmjGoodInfo = tSmjGoodLists.get(0);
        logger.info("获取金额为：{} 商品信息：{}", amount, JSONObject.toJSONString(tmpSmjGoodInfo));
        tSmjGoodLists.remove(0);
//        tmpSmjGoodInfo.setGoodStatus(1);
//        itSmjGoodListService.updateTSmjGoodList(tmpSmjGoodInfo);
        logger.info("获取金额为：{}的商品后缓存的商品个数：{}", amount, tSmjGoodLists.size());
        if (tOrderInfo.getChannel().contains("alipay")) {
            redisUtil.set("PLATFORM_SMJXLMALI"+tUserRecipientInfo.getId()+amount + "", tSmjGoodLists);
        } else {
            redisUtil.set("PLATFORM_SMJXLMWX"+tUserRecipientInfo.getId()+amount + "", tSmjGoodLists);
        }
        return tmpSmjGoodInfo;

    }

    @Override
    public JSONObject createPayOrder(TOrderInfo orderInfo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        synchronized (this) {
            TSmjGoodList tmpSmjGoodInfo = getPayInfoObj(userRecipientInfo, orderInfo);
            if (tmpSmjGoodInfo == null) {
                jsonObject.put("code", "100");
                jsonObject.put("msg", "通道异常,请稍后再试！未匹配通道收款账号");
                logger.info("========修改收款账号为不可用===============");
                return jsonObject;
            }
            TSmjMachineList tSmjMachineList = itSmjMachineListService.selectTSmjMachineListById(tmpSmjGoodInfo.getMachineId());



            HashMap<String, String> dataMap = new HashMap();
            HashMap<String, String> headMap = new HashMap();
            if (orderInfo.getChannel().contains("alipay")) {
                headMap.put("User-Agent", "Mozilla/5.0 (Linux; Android 9; PJU110 Build/PQ3A.190801.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/105.0.5195.148 MYWeb/0.11.0.240912194432 UWS/3.22.2.9999 UCBS/3.22.2.9999_220000000000 Mobile Safari/537.36 NebulaSDK/1.8.100112 Nebula AlipayDefined(nt:WIFI,ws:360|0|2.0) AliApp(AP/10.6.50.8000) AlipayClient/10.6.50.8000 Language/zh-Hans useStatusBar/true isConcaveScreen/false Region/CNAriver/1.0.0");
            } else {
                headMap.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.53(0x18003530) NetType/WIFI Language/zh_CN");
            }
            //https://vm.smshj.com/hbshengma/mobile/payInfo_alipay.html?p=490C5A18799995DBD5CF9A8614414B9F371DF2930C46054E84D7AD76AA275F2C
            //https://vm.smshj.com/hbshengma/mobile/submitpay_alipay_company.action
            String payInfo = "";
            String regionCode = "";
            HttpResponse httpResponse = null;
            if (StringUtils.isNotBlank(userRecipientInfo.getCity())) {
                regionCode = userRecipientInfo.getCity();
            } else if (StringUtils.isNotBlank(userRecipientInfo.getProvince())) {
                regionCode = userRecipientInfo.getProvince();
            }
            JSONObject proxyObj = new JSONObject();
            dataMap.put("vmCode", tSmjMachineList.getMachineName());
            if (StringUtils.isNotBlank(regionCode)) {
                proxyObj = commonService.getPoxyIp(regionCode);
                //httpResponse = HttpUtils.httpFormPost("https://vmpay.aotaki.com/trade/generateSellUrl", headMap, "", dataMap, "售货机【小懒猫】", proxyObj.getString("ip") + ":" + proxyObj.getString("prot"));
                orderInfo.setProxyIp(proxyObj.getString("ip") + ":" + proxyObj.getString("prot"));
            } else {
                //httpResponse = HttpUtils.httpFormPost("https://vmpay.aotaki.com/trade/generateSellUrl", headMap, "", dataMap, "售货机【小懒猫】", "");
            }
//            JSONObject generateSellUrlObj = JSONObject.parseObject(httpResponse.getBody());
//            logger.info("generateSellUrlObj请求返回：{}", generateSellUrlObj);
//            if (StringUtils.isNotBlank(regionCode)) {
//                httpResponse = HttpUtils.httpFormGet(generateSellUrlObj.getString("sellUrl"), headMap, "", "售货机【小懒猫】", proxyObj.getString("ip") + ":" + proxyObj.getString("prot"));
//            } else {
//                httpResponse = HttpUtils.httpFormGet(generateSellUrlObj.getString("sellUrl"), headMap, "", "售货机【小懒猫】", "");
//            }
            JSONObject atkAdParams = new JSONObject();
            atkAdParams.put("sysId","vm_xxh");
            atkAdParams.put("customerId","25738237");
            atkAdParams.put("saleLocId",tSmjMachineList.getSmMachineId());
            String tmpUrl = "https://vmpay.aotaki.com/trade/subRackIndex.html?atkAdParams="+ URLEncoder.encode(atkAdParams.toJSONString()) +"&rackNo="+tmpSmjGoodInfo.getGoodHd()+"&v=66&customerId=25738237&vmCode="+tSmjMachineList.getMachineName();
            logger.info("sellUrl请求地址：{}", tmpUrl);

            if (StringUtils.isNotBlank(regionCode)) {
                httpResponse = HttpUtils.httpFormGet(tmpUrl, headMap, "", "售货机【小懒猫】", proxyObj.getString("ip") + ":" + proxyObj.getString("prot"));
            } else {
                httpResponse = HttpUtils.httpFormGet(tmpUrl, headMap, "", "售货机【小懒猫】", "");
            }
            logger.info("sellUrl请求返回：{}", httpResponse.getIsSuccess());
            //https://vmpay.aotaki.com/trade/c1/init
            dataMap = new HashMap();
            dataMap.put("vmCode", tSmjMachineList.getMachineName());
            dataMap.put("rackNo", tmpSmjGoodInfo.getGoodHd());

            if (StringUtils.isNotBlank(regionCode)) {
                httpResponse = HttpUtils.httpFormPost("https://vmpay.aotaki.com/trade/c1VmOrderDetail", headMap, "", dataMap, "售货机【小懒猫】", proxyObj.getString("ip") + ":" + proxyObj.getString("prot"));
            } else {
                httpResponse = HttpUtils.httpFormPost("https://vmpay.aotaki.com/trade/c1VmOrderDetail", headMap, "", dataMap, "售货机【小懒猫】", "");
            }
            JSONObject payInfoObj = JSONObject.parseObject(httpResponse.getBody());
            //String payInfo = HttpUtils.submit(goodUrls[0] + "submitpay_alipay_company.action", dataMap);
            logger.info("c1VmOrderDetail请求返回：{}", payInfoObj);

            /**
             * {
             * 	"msg": "成功",
             * 	"code": "10000",
             * 	"success": true,
             * 	"barCode": "https://qr.alipay.com/bax06135jbm8boeehl7q55dc"
             * }
             */
            String payUrl = "";
            if (payInfoObj.getBoolean("success")) {
                String orderKey = payInfoObj.getJSONObject("detail").getString("orderKey");
                dataMap = new HashMap();
                dataMap.put("vmCode", tSmjMachineList.getMachineName());
                dataMap.put("key", orderKey);
                dataMap.put("sysFlg", "1");
                logger.info("getPayments请求参数：{}", JSONObject.toJSONString(dataMap));
                if (StringUtils.isNotBlank(regionCode)) {
                    httpResponse = HttpUtils.httpFormPost("https://vmpay.aotaki.com/trade/getPayments", headMap, "", dataMap, "售货机【小懒猫】", proxyObj.getString("ip") + ":" + proxyObj.getString("prot"));
                }else{
                    httpResponse = HttpUtils.httpFormPost("https://vmpay.aotaki.com/trade/getPayments", headMap, "", dataMap, "售货机【小懒猫】", "");
                }
                JSONObject paymentsObj = JSONObject.parseObject(httpResponse.getBody());
                logger.info("getPayments返回：" + paymentsObj.toJSONString());
                if (!paymentsObj.getBooleanValue("success")) {
                    tmpSmjGoodInfo.setGoodStatus(0);
                    itSmjGoodListService.updateTSmjGoodList(tmpSmjGoodInfo);
                    jsonObject.put("code", "100");
                    jsonObject.put("msg", "获取连接失败" + payInfoObj.getString("msg"));
                    return jsonObject;
                }
                if (StringUtils.isNotBlank(regionCode)) {
                    httpResponse = HttpUtils.httpFormGet("https://vmpay.aotaki.com/trade/payChoose.html?key=" + orderKey + "&sysFlg=1&vmCode=" + tSmjMachineList.getMachineName(), headMap, "", "售货机【小懒猫】", proxyObj.getString("ip") + ":" + proxyObj.getString("prot"));
                } else {
                    httpResponse = HttpUtils.httpFormGet("https://vmpay.aotaki.com/trade/payChoose.html?key=" + orderKey + "&sysFlg=1&vmCode=" + tSmjMachineList.getMachineName(), headMap, "", "售货机【小懒猫】", "");
                }
                logger.info("payChoose返回：" + httpResponse.getIsSuccess());
//                payUrl = "https://vmpay.aotaki.com/trade/payChoose.html?key=" + orderKey + "&sysFlg=1&vmCode=" + tSmjMachineList.getMachineName();
                if (orderInfo.getChannel().contains("alipay")) {
                    payUrl = "https://vmpay.aotaki.com/trade/c1VmAuth?key=" + orderKey + "&userId="+orderInfo.getAliUserId()+"&payment=01&authCode=";
                }else{
                    payUrl = "https://vmpay.aotaki.com/trade/c1VmAuth?key=" + orderKey + "&userId="+orderInfo.getAliUserId()+"&payment=02&authCode=";
                }
                String outTradeNo = paymentsObj.getJSONObject("activityParams").getString("outTradeNo");
                orderInfo.setQrcodeContent(tSmjMachineList.getMachineName());
                orderInfo.setQrcodeTxt(tmpSmjGoodInfo.getId() + "");
                orderInfo.setGoodsName(orderKey + "");
//                    tmpSmjGoodInfo.setGoodStatus(1);
                itSmjGoodListService.updateTSmjGoodList(tmpSmjGoodInfo);
                orderInfoService.updateTOrderInfo(orderInfo);

                jsonObject.put("payUrl", payUrl);
                jsonObject.put("orderNo", outTradeNo);
                jsonObject.put("code", "200");
                logger.info("==========开始更新订单状态为处理中=================" + jsonObject.toJSONString());
                return jsonObject;
            } else {
                tmpSmjGoodInfo.setGoodStatus(0);
                itSmjGoodListService.updateTSmjGoodList(tmpSmjGoodInfo);
                jsonObject.put("code", "100");
                jsonObject.put("msg", "获取连接失败" + payInfoObj.getString("msg"));
                return jsonObject;
            }
        }
    }

    @Override
    public ResponseData smartReissueOrder(TOrderInfo orderInfo) throws Exception {
        return new ResponseData();
    }
}
